package com.spm.librarianmanagersystem.controller;

import com.alibaba.fastjson.JSONObject;
import com.spm.librarianmanagersystem.pojo.Member;
import com.spm.librarianmanagersystem.service.UserInfoService;
import com.spm.librarianmanagersystem.utils.JsonResult;
import com.spm.librarianmanagersystem.utils.UserContextHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/user/profile")
public class UserInfoController {
    @Autowired
    private UserInfoService uis;

    @GetMapping("/detail")
    public JsonResult<JSONObject> getUserProfileDetail() {
        // 这里统一从UserContextHolder（token）中获取member表里的id属性 即学工号
        String currentUserId = UserContextHolder.getCurrentUserId();
        return new JsonResult<>(uis.getUserProfileDetail(currentUserId));
    }

    @GetMapping("/admin")
    public JsonResult<JSONObject> getAdminProfileDetail() {
        String adminId = "admin";
        return new JsonResult<>(uis.getAdminProfileDetail(adminId));
    }

    @PostMapping("/edit")
    public JsonResult<Member> editUserProfile(@RequestBody JSONObject object) {
        Member member = uis.editUserProfile(object);
        if (member == null) {
            return new JsonResult<>(null, 1, "修改用户信息失败");
        }
        return new JsonResult<>(member);
    }

    @PostMapping("/updateReputation")
    public JsonResult<Void> updateReputation(@RequestBody JSONObject object){
        String currentUserId = UserContextHolder.getCurrentUserId();
        //System.out.println("更新信誉值！！！！！" + currentUserId);
        int change = object.getInteger("change");
        boolean success = uis.updateReputation(currentUserId, change);
        if (!success) {
            return new JsonResult<>(null, 1, "更新信誉值失败");
        }
        return new JsonResult<>(null, 0, "更新信誉值成功");
    }
}


